<?php
HBase::using('DAL.HUsers');

class HAuthentication {
	function check() {
		$page_alias = HApplication::getCurrentAlias();
		$page_id = HPages::getPageIdByAlias($page_alias);
				
		// If no Session --> redirect to HOME
		if (!isset($_SESSION['HNS_SYSTEM'])) HUtil::redirect('login.php');
		// Else: get Session info (username, userId, userRoleId), assign to $session_object. Start authenticate		
		
		// Collect All Roles from Session
		
		// Authenticate Role		
		
		// Authenticate User
		
	}
	
	function login($username, $password) {
		// Collect userid, username, role default, role in others
		$a = HSql::fetch2Array(HSql::doQuery('SELECT * FROM portal_users'));
		for ($i = 0; $i < count($a); $i++) {
			if ($a[$i]['username'] == $username && $a[$i]['password'] == md5($password)) {				
				// Get all roles
				$roles = self::getAllRoles(HUsers::getIdByUsername($a[$i]['username']));
				
				// Set session -- this may change 
				$arr = array(
					'username'=>$username,
					'userid'=>HUsers::getIdByUsername($a[$i]['username']),
					'roles'=>$roles
				);
				
				// assign session
				$_SESSION['HNS_SYSTEM'] = $arr;
				// return
				return true;
			}
		}
		return false;
	}	
	
	function getAllRoles($user_id) {		
		// Default role
		$a = array();				
		$a[] = self::getDefaultRole($user_id);		
		// Get other roles
		$b = HSql::fetch2Array(HSql::doQuery("SELECT * FROM portal_roles_users WHERE user_id = '$user_id'"));				
		if (count($b) == 0) return $a;
		else {
			for ($i = 0; $i < count($b); $i++) {
				$a[$i + 1] = $b[$i]['role_id'];
			}
			return $a;
		}
	}
	
	function getDefaultRole($user_id) {
		$a = HSql::fetch2Array(HSql::doQuery("SELECT * FROM portal_users WHERE id = '$user_id'"));			
		return $a[0]['role_id'];
	}
	
	function isLogged() {
		if (!isset($_SESSION['HNS_SYSTEM'])) return false;
		else return true;
	}
	
	/* 
		Session object contains
		'username', 'userid', 'role'=>array('role1_id','rol2')
	*/
	public $session_object;
}

?>